package handler

import (
	"context"
	"encoding/json"
	"fmt"
	"go_final/mxshop_srvs/goods_srv/global"
	"go_final/mxshop_srvs/goods_srv/model"
	goodspb "go_final/mxshop_srvs/goods_srv/proto/protofile"

	"gorm.io/gorm"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"google.golang.org/protobuf/types/known/emptypb"
)

func (s Server) GetAllCategorysList(c context.Context, empty *emptypb.Empty) (*goodspb.CategoryListResponse, error) {
	var categories []model.Category
	res := global.DB.Where(map[string]interface{}{
		"level": 1,
	}).Preload("SubCategories.SubCategories").Find(&categories)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	rsp := &goodspb.CategoryListResponse{}
	// rsp.Total = int32(res.RowsAffected)	// 这里只有一级分类的数量

	for _, cate := range categories {
		//TODO 需要写递归来添加, 要不然只有一级分类
		rsp.Data = append(rsp.Data, &goodspb.CategoryInfoResponse{
			Id:             cate.ID,
			Name:           cate.Name,
			ParentCategory: cate.ParentCategoryID,
			Level:          cate.Level,
			IsTab:          cate.IsTap,
		})
	}

	b, _ := json.Marshal(categories)
	rsp.JsonData = string(b)

	return rsp, nil
}

func (s Server) GetSubCategory(c context.Context, request *goodspb.CategoryListRequest) (*goodspb.SubCategoryListResponse, error) {
	var category model.Category
	res := global.DB.First(&category, request.Id)
	if res.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "分类不存在")
	}

	var categories []*model.Category
	sub := "" // 默认是三级, 不需要查询子分类
	if category.Level == 1 {
		// 查询二级和三级
		sub = "SubCategories.SubCategories"
	} else if category.Level == 2 {
		// 查询三级
		sub = "SubCategories"
	}

	res = global.DB.Where(&model.Category{
		ParentCategoryID: request.Id,
	}).Preload(sub).Find(&categories)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	fmt.Println("categories", categories)

	rsp := &goodspb.SubCategoryListResponse{
		Total: int32(res.RowsAffected),
		Info: &goodspb.CategoryInfoResponse{
			Id:             category.ID,
			Name:           category.Name,
			ParentCategory: category.ParentCategoryID,
			Level:          category.Level,
			IsTab:          category.IsTap,
		},
	}

	// 添加子分类进来(只添加下面的一层)
	for _, cate := range categories {
		rsp.SubCategorys = append(rsp.SubCategorys, &goodspb.CategoryInfoResponse{
			Id:             cate.ID,
			Name:           cate.Name,
			ParentCategory: cate.ParentCategoryID,
			Level:          cate.Level,
			IsTab:          cate.IsTap,
		})
	}

	return rsp, nil
}

func (s Server) CreateCategory(c context.Context, request *goodspb.CategoryInfoRequest) (*goodspb.
	CategoryInfoResponse, error) {
	var category *model.Category
	res := global.DB.Where(&model.Category{
		Name: request.Name,
	}).First(&category)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	if res.RowsAffected > 0 {
		return nil, status.Error(codes.AlreadyExists, "分类已经存在")
	}

	// 开始新建分类
	category.Name = request.Name
	category.Level = request.Level
	category.IsTap = request.IsTab
	if category.Level != 1 {
		category.ParentCategoryID = request.ParentCategory
	}

	res = global.DB.Create(&category)
	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	return &goodspb.CategoryInfoResponse{
		Id: category.ID,
	}, nil
}

func (s Server) DeleteCategory(c context.Context, request *goodspb.DeleteCategoryRequest) (*emptypb.Empty, error) {
	category := model.Category{}
	res := global.DB.Delete(&category, request.Id)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	return &emptypb.Empty{}, nil
}

func (s Server) UpdateCategory(c context.Context, request *goodspb.CategoryInfoRequest) (*emptypb.Empty, error) {
	category := model.Category{}

	if request.Name != "" {
		category.Name = request.Name
	}

	if request.ParentCategory != 0 {
		category.ParentCategoryID = request.ParentCategory
	}

	if request.Level != 0 {
		category.Level = request.Level
	}

	category.IsTap = request.IsTab

	res := global.DB.Model(&model.Category{
		BaseModel: model.BaseModel{
			ID: request.Id,
		},
	}).Updates(&category)

	if res.Error != nil && res.Error != gorm.ErrRecordNotFound {
		return nil, status.Error(codes.Internal, res.Error.Error())
	}

	return &emptypb.Empty{}, nil
}
